{% extends 'admin/dashboard.html' %}

{% block content %}
<div class="card">
    <h2 class="text-xl font-bold mb-4">{% if product %}编辑产品{% else %}添加产品{% endif %}</h2>
    <form id="productForm" enctype="multipart/form-data">
        <div class="mb-4">
            <label for="name" class="block text-sm font-medium text-gray-700">名称</label>
            <input type="text" id="name" name="name" value="{{ product.name if product else '' }}" required class="mt-1 p-2 w-full border rounded-md">
        </div>
        <div class="mb-4">
            <label for="description" class="block text-sm font-medium text-gray-700">描述</label>
            <textarea id="description" name="description" rows="4" required class="mt-1 p-2 w-full border rounded-md">{{ product.description if product else '' }}</textarea>
        </div>
        <div class="mb-4">
            <label for="image" class="block text-sm font-medium text-gray-700">图片</label>
            <input type="file" id="image" name="image" class="mt-1 p-2 w-full">
            {% if product and product.image_url %}
                <img src="{{ product.image_url }}" alt="产品图片" class="mt-2 max-w-xs">
            {% endif %}
        </div>
        <button type="button" class="px-4 py-2 bg-primary text-white rounded" onclick="submitForm({{ product.id if product else '' }})">
            {% if product %}更新{% else %}提交{% endif %}
        </button>
    </form>
</div>

<script>
function submitForm(productId) {
    const form = document.getElementById('productForm');
    const formData = new FormData(form);
    const method = productId ? 'PUT' : 'POST';
    const url = productId ? `/api/products/${productId}` : '/api/products/add';

    fetch(url, {
        method: method,
        body: formData
    })
   .then(response => response.json())
   .then(data => {
        console.log(data);
        window.location.href = '/admin/products/list';
    })
   .catch(error => console.error('Error:', error));
}
</script>
{% endblock %}